package com.xzxy.xmlg_backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xzxy.xmlg_backend.entity.Result;
import com.xzxy.xmlg_backend.entity.Student;
import com.xzxy.xmlg_backend.entity.dto.StudentDto;
import com.xzxy.xmlg_backend.entity.vo.StudentVo;
import com.xzxy.xmlg_backend.service.impl.StudentServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/students")
@Tag(name = "学员管理")
public class StudentController {

    @Autowired
    private StudentServiceImpl studentService;

    @PostMapping("/list")
    @Operation(summary = "分页查询", description = "分页查询信息")
    public Result page(@RequestBody StudentDto studentDto) {
        Page<Student> page = new Page<>(studentDto.getPage(), studentDto.getPageSize());
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        if (studentDto.getName() != null && !studentDto.getName().isEmpty()) {
            wrapper.like(Student::getName, studentDto.getName());
        }
        if (studentDto.getClassId() != null) {
            wrapper.eq(Student::getClassId, studentDto.getClassId());
        }
        wrapper.orderByDesc(Student::getUpdatedAt); // 根据更新时间降序排序

        studentService.page(page, wrapper);

        StudentVo studentVo = new StudentVo();
        studentVo.setRows(page.getRecords());
        studentVo.setTotal(page.getTotal());
        return Result.success(studentVo);
    }

    /**
     * 根据id查询学生信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据id查询学生",description = "根据id查询学生信息")
    public Result getById(@PathVariable Long id){
        return Result.success(studentService.getById(id));
    }

    /**
     * 新增学生信息
     * @param student
     * @return
     */
    @PostMapping
    @Operation(summary = "新增学生",description = "新增学生信息")
    public Result add(@RequestBody Student student){
        student.setCreatedAt(LocalDateTime.now());
        student.setUpdatedAt(LocalDateTime.now());
        boolean b = studentService.save(student);
        if (b)
            return Result.success();
        return Result.fail("新增员工失败，请稍后再试！");
    }

    /**
     * 修改学生信息
     * @param student
     * @return
     */
    @PutMapping
    @Operation(summary = "修改学生",description = "修改学生信息")
    public Result update(@RequestBody Student student){
        student.setUpdatedAt(LocalDateTime.now());
        boolean b = studentService.updateById(student);
        if (b)
            return Result.success();
        return Result.fail("修改员工失败，请稍后再试！");
    }

    /**
     * 删除学生信息
     * @param ids
     * @return
     */
    @DeleteMapping("/{ids}")
    @Operation(summary = "删除学生",description = "删除学生信息")
    public Result delete(@PathVariable List<Long> ids){
        boolean b = studentService.removeByIds(ids);
        if (b)
            return Result.success();
        return Result.fail("删除员工失败，请稍后再试！");
    }

    /**
     * 获取学生统计数据
     * @return
     */
    @GetMapping("/stats")
    @Operation(summary = "获取学生统计数据", description = "获取学生各项统计信息")
    public Result getStudentStats(){
        // 总学生数
        long totalStudents = studentService.count();

        // 在读学生数
        LambdaQueryWrapper<Student> activeWrapper = new LambdaQueryWrapper<>();
        activeWrapper.eq(Student::getStatus, 1);
        long activeStudents = studentService.count(activeWrapper);

        // 已离开学生数
        LambdaQueryWrapper<Student> inactiveWrapper = new LambdaQueryWrapper<>();
        inactiveWrapper.eq(Student::getStatus, 0);
        long inactiveStudents = studentService.count(inactiveWrapper);

        // 男学生数
        LambdaQueryWrapper<Student> maleWrapper = new LambdaQueryWrapper<>();
        maleWrapper.eq(Student::getGender, 1);
        long maleStudents = studentService.count(maleWrapper);

        // 女学生数
        LambdaQueryWrapper<Student> femaleWrapper = new LambdaQueryWrapper<>();
        femaleWrapper.eq(Student::getGender, 2);
        long femaleStudents = studentService.count(femaleWrapper);

        // 按班级统计
        List<Student> allStudents = studentService.list();
        Map<Integer, Long> classCounts = allStudents.stream()
                .collect(Collectors.groupingBy(Student::getClassId, Collectors.counting()));

        // 按入学年份统计
        Map<String, Long> yearCounts = allStudents.stream()
                .collect(Collectors.groupingBy(
                        student -> student.getJoinDate().getYear() + "",
                        Collectors.counting()
                ));

        Map<String, Object> stats = new HashMap<>();
        stats.put("totalStudents", totalStudents);
        stats.put("activeStudents", activeStudents);
        stats.put("inactiveStudents", inactiveStudents);
        stats.put("maleStudents", maleStudents);
        stats.put("femaleStudents", femaleStudents);
        stats.put("classCounts", classCounts);
        stats.put("yearCounts", yearCounts);

        return Result.success(stats);
    }
}
